import React, { useState, useEffect } from 'react'
import { View, Text, Input } from '@tarojs/components'
import { toast } from '@/utils/utils'
import { Space, } from '@/components/UiComponents';
import { AtIcon } from 'taro-ui'
import Taro from "@tarojs/taro";
import { fetchGoodsBuyPageInfo, fetchUserNeedInformationCollection, fakeCalculateOrderPrice, fakeSubmitOrder } from '@/server/order';
import { backgroundObj, loginData } from '@/utils/utils'
import "taro-ui/dist/style/components/icon.scss";
import { getCurrentInstance, useReachBottom } from '@tarojs/taro'
import Router from '@/utils/router';
import { fetchListUserAddress } from '@/server/shop';
import MaskCollection from './components/MaskCollection'
import MaskAddress from './components/MaskAddress';
import './index.scss'
const Card = (props) => {
  const { data, open } = props
  const { receiveUsername, cityName, districtName, provinceName, address, id, receiveMobile } = data
  return <View onClick={() => {
    open({
      show: true,
      detail: data
    })
  }} className='address-wrapper'>
    <View className='left-info'>
      <View className='top-text'>{
        receiveUsername
      } <Text style={{ paddingLeft: 12 }}>{receiveMobile}</Text></View>
      <View className='address-text'>{provinceName + cityName + districtName + address}</View>
    </View>
    <View className='edit-icon'>
      <View style={{ fontSize: Taro.pxTransform(42) }} className="at-icon at-icon-chevron-right"
      ></View>
    </View>
  </View>
}

const CardEmpty = (props) => {
  const { open, data } = props
  return <View onClick={() => {
    open({
      show: true,
      detail: data
    })
  }} className='address-wrapper'>
    <View className='left-info'>
      <View className='top-text'>
        请先添加收货地址
      </View>
    </View>
    <View className='edit-icon'>
      <View style={{ fontSize: Taro.pxTransform(42) }} className="at-icon at-icon-chevron-right"
      ></View>
    </View>
  </View>
}
const PayOrder = (props) => {
  const { params } = getCurrentInstance().router
  const { goodsId, skuId, count = '1', fromGoodsId } = params
  const [price, setPriceData] = useState({ totalPrice: 0 })
  const { username, unionId, openId, organizationId, profile, token, shareType } = loginData() || {}
  const [buyCount, setBuyCount] = useState(count)
  const [buyCountType, setBuyCountType] = useState(false)
  const [remark, setRemark] = useState('')
  const [data, setData] = useState({})
  const [addressObj, setAddressObj] = useState(null)
  const [addressList, setAddressList] = useState([])
  const [addressVisible, setAddressVisible] = useState([])
  const [collection, setCollection] = useState({})
  let interval = null
  const { goodsBaseInfo = {},
    goodsSku = {}, buyInfo = {}, buyOrganizationInfo
    = {}
  } = data
  const { priceType = 'free', price: priceInfo, goodsCommerceId, secKillId, secKillSkuId } = buyInfo
  const { organizationName } = buyOrganizationInfo
  const { picture = '', goodsName, buyLimit
    , buyLimitFlag, goodsType = '' } = goodsBaseInfo
  const { propertyDesc, } = goodsSku

  useEffect(() => {
    if (buyCountType && priceType !== 'free' || goodsType === 'offline') {
      if (interval) {
        clearTimeout(interval)
        interval = setTimeout(() => {
          fetchPrice()
        }, 300)
      }
      else {
        interval = setTimeout(() => {
          fetchPrice()
        }, 300)
      }

    }
  }, [buyCount])
  useEffect(() => {
    if (buyCountType && priceType !== 'free' || goodsType === 'offline') {

      if (interval) {
        clearTimeout(interval)
        interval = setTimeout(() => {
          fetchPrice()
        }, 300)
      }
      else {
        interval = setTimeout(() => {
          fetchPrice()
        }, 300)
      }

    }
  }, [addressObj])
  const fetchData = () => {
    const { username, unionId, openId, organizationId, profile, token } = loginData() || {}
    fetchGoodsBuyPageInfo({ organizationId, goodsId, skuId, fromGoodsId, }).then(e => {
      const { goodsBaseInfo = {}, buyInfo = {} } = e
      const { goodsType = '', } = goodsBaseInfo
      const { price } = buyInfo
      if (goodsType !== 'offline') {
        setPriceData({
          totalPrice: price
        })
      }
      setBuyCountType(() => {
        setData(e)
        return true
      })
    })

  }
  const fetchUserNeedInformation = () => {
    const { username, unionId, openId, organizationId, profile, token } = loginData() || {}
    fetchUserNeedInformationCollection({ unionId, organizationId, goodsId, informationCollectionPage: 'pagePay', }).then(e => {
      const { checkInformationCollection = {}, informationCollection = {} } = e
      const { needFlag } = checkInformationCollection
      const { editFlag } = informationCollection
      setCollection({
        show: needFlag === '1' && editFlag !== '1',
        detail: informationCollection
      })
    })
  }
  const fetchPrice = async () => {
    const e = await fakeCalculateOrderPrice({
      organizationId,
      goodsId,
      skuId,
      goodsAmount: buyCount,
      fromGoodsId,
      userAddressId: addressObj ? addressObj.id : ''
    })
    const { expressPrice, price, promoterPrice, totalPrice } = e
    setPriceData({
      price: shareType === 'promote' ? e.promoterPrice ? e.promoterPrice : e.price : e.price,
      totalPrice,
      expressPrice
    })
    // .then(e => {

    // })
  }

  const fetchAddress = () => {
    fetchListUserAddress({ page: 1, limit: 99 }).then(val => {
      const { userAddressList } = val
      setAddressList(userAddressList)
      if (userAddressList.length > 0) {
        setAddressObj(userAddressList[0])
      }
    })


  }
  useEffect(() => {
    if (goodsType === 'offline') {
      fetchAddress()
    }
  }, [data])
  useEffect(() => {
    fetchData()
    fetchUserNeedInformation()
  }, [])
  const changeRule = (type) => {
    if (type === 'add') {
      if (buyLimitFlag === '1') {
        if (buyLimit > buyCount) {
          return true
        }
        else {
          return false
        }
      }
      else {
        return true
      }
    }
    else {
      if (buyCount > 1) {
        return true
      }
      else return false
    }
  };
  const onChange = (e) => {
    if (buyLimitFlag === '1') {
      if (buyLimit > e) {
        if (e <= 0) {
          setBuyCount(1)
        }
        else {
          setBuyCount(e)
        }
      }
      else {
        setBuyCount(e)
      }
    }


  }
  //过滤校验条件
  const changeCount = (type) => {
    if (changeRule(type)) {
      if (type === "add") {
        setBuyCount(
          Number(buyCount) + 1);
      } else {
        setBuyCount(Number(buyCount) - 1);
      }
    } else {
      if (type === "add") {
        toast("库存不足或购买数量超过上限");
      } else {
        toast("选择数量不能小于1");
      }
    }
  };
  const fakeSubmitOrderHandle = () => {
    const userInfo = loginData()
    const { organizationId, token } = loginData() || {}
    let payload = {
      goodsAmount: buyCount,
      remark: remark,
      organizationId,
      ...userInfo,
      goodsId: goodsId,
      skuId: skuId,
      goodsType,
      fromGoodsId,
      userAddressId: addressObj ? addressObj.id : ''
    }
    if (goodsType === 'offline' && !addressObj) {
      return toast('请先选择地址')
    }
    if (goodsCommerceId) {
      payload.goodsCommerceId = goodsCommerceId
    }
    if (secKillId) {
      payload.secKillId = secKillId
    }
    if (secKillSkuId) {
      payload.secKillSkuId = secKillSkuId
    }
    if (token) {
      fakeSubmitOrder(payload).then(e => {
        const { priceType, orderSn, needPayFlag } = e
        if (needPayFlag === '0') {
          Router('payShopDetail', { args: { goodsId: goodsId } })
          toast('支付成功')
        }
        else {
          Router('orderWeex', { args: { orderSn: orderSn, linkType: 'redirectTo' } })
          //  window.location.replace()
        }
      })
    }
    else {
      Router('login')
    }
  }
  console.log(price, 'price')
  return (
    <View className='payOrder_box'>
      {goodsType === 'offline' ? addressObj ? <Card open={setAddressVisible} data={addressObj}></Card> : <CardEmpty open={setAddressVisible}></CardEmpty> : ''}
      <View className='payOrder_content'>
        <View className='payOrder_top'>
          <AtIcon value={'shopping-bag'}></AtIcon>
          <View className='payOrder_title'>{organizationName}</View>
        </View>
        <View className='payOrder_shopCard'>
          <View className='payOrder_profile' style={backgroundObj(picture.split(',')[0])}></View>
          <View className='payOrder_shop'>
            <View className='payOrder_shop_title'> {goodsName} </View>
            {propertyDesc && <View className='payOrder_shop_sku'>{propertyDesc}</View>}
            <View className='payOrder_shop_tagBox'>
              {buyLimitFlag === '1' ? <View className='payOrder_shop_tag'>限购{buyLimit}件</View> : null}
            </View>
            <View className='payOrder_shop_price'>
              <View className='payOrder_shop_priceLeft'>{priceType === 'free' ? '免费' : <View>
                <Text className='payOrder_shop_TextLeft'>¥ </Text> {(priceInfo)}</View>}</View>
              <View className='payOrder_shop_priceRight'>
                {goodsType === 'offline' ? <Space>
                  <AtIcon value='subtract-circle' onClick={() => changeCount('remove')}></AtIcon>
                  <Input onChange={(e) => onChange(e)} type='number' value={buyCount} className='payOrder_shop_input'></Input>
                  <AtIcon value='add-circle' onClick={() => changeCount('add')}></AtIcon>
                </Space> : <View className='payOrder_shop_noInput'>x{buyCount}</View>}
              </View>
            </View>
          </View>
        </View>

      </View>
      <View className='payOrder_Input_box'>
        <View className='payOrder_Input_label'>留言</View>
        <Input placeholder='请输入您的备注' value={remark} onChange={(e) => { setRemark(e) }} className='payOrder_Input_value'></Input>
      </View>
      {
        goodsType === 'offline' && <>
          <View className='payOrder_Input_box'>
            <View className='payOrder_Input_label'>商品金额：¥ {(price.price)},运费：¥ {(price.expressPrice)}</View>
          </View>
        </>
      }
      <View className='payOrder_fixed'>
        <View className='payOrder_fixed_price'>
          ¥ {(price.totalPrice)}
        </View>
        <View className='payOrder_fixed_btn' onClick={fakeSubmitOrderHandle}>提交订单</View>
      </View>
      <MaskCollection visible={collection} onClose={(e) => {
        setCollection({
          ...collection,
          show: false
        })
      }} ></MaskCollection>
      <MaskAddress setAddressObj={setAddressObj} visible={addressVisible} onClose={() => setAddressVisible(false)}></MaskAddress>
    </View>
  )
}
export default PayOrder
